<template>
  <div class="fleet-list">
    <!-- 车队列表 -->
    <div v-show="!showVehicleList">
      <el-card>
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-medium">车队列表</span>
            <el-button type="primary" :icon="CirclePlus" @click="openFleetForm('新增车队')">
              新增车队
            </el-button>
          </div>
        </template>
        
        <ProTable
          ref="proTableRef"
          :columns="columns"
          :search-columns="searchColumns"
          :request-api="getTableList"
          :init-param="{ companyId: props.companyId }"
          row-key="id"
        >
          <template #operation="{ row }">
            <el-button
              type="primary"
              link
              :icon="View"
              @click="showVehicles(row)"
            >
              查看车辆
            </el-button>
            <el-button
              type="primary"
              link
              @click="bindDevice(row)"
            >
              绑定设备
            </el-button>
            <el-button
              type="primary"
              link
              :icon="EditPen"
              @click="openFleetForm('编辑车队', row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              :icon="Delete"
              @click="deleteFleet(row)"
            >
              删除
            </el-button>
          </template>
        </ProTable>
      </el-card>
    </div>
    
    <!-- 车辆列表 -->
    <div v-show="showVehicleList">
      <el-page-header @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> {{ currentFleet?.name }} - 车辆列表 </span>
        </template>
      </el-page-header>
      <VehicleList v-if="currentFleet" :fleet-id="currentFleet.id" />
    </div>
    
    <!-- 车队表单 -->
    <FleetForm ref="fleetFormRef" />
    
    <!-- 设备绑定表单 -->
    <DeviceBindingForm ref="deviceBindingFormRef" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { CirclePlus, EditPen, Delete, View } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import ProTable from '@/components/ProTable/index.vue';
import {
  getFleetListApi,
  createFleetApi,
  updateFleetApi,
  removeFleetApi
} from '@/api/modules/dept/dept';
import { useHandleData } from '@/hooks/useHandleData';
import FleetForm from '@/views/dept/deptList/components/FleetForm.vue';
import DeviceBindingForm from '@/views/dept/deptList/components/DeviceBindingForm.vue';
import VehicleList from '@/views/dept/deptList/VehicleList.vue';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import type { DeptQuery, DeptRow } from '@/api/types/dept/dept';

defineOptions({
  name: 'FleetList'
});

const props = defineProps<{
  companyId: number;
}>();

const proTableRef = ref<ProTableInstance>();
const fleetFormRef = ref<InstanceType<typeof FleetForm>>();
const deviceBindingFormRef = ref<InstanceType<typeof DeviceBindingForm>>();

// 控制显示哪个页面
const showVehicleList = ref(false);
const currentFleet = ref<DeptRow | null>(null);

// 表格配置项
const columns: ColumnProps<DeptRow>[] = [
  { prop: 'name', label: '车队名称', width: 200 },
  { prop: 'sort', label: '排序', width: 100 },
  { 
    prop: 'leaders', 
    label: '负责人',
    width: 200,
    render: ({ row }) => {
      if (row.leaders && row.leaders.length > 0) {
        return row.leaders.map((leader: any) => leader.name).join(', ');
      }
      return '-';
    }
  },
  { prop: 'createTime', label: '创建时间',},
  { prop: 'updateTime', label: '更新时间', width: 180 },
  { prop: 'operation', label: '操作', fixed: 'right' }
];

// 搜索条件项
const searchColumns = ref<SearchProps[]>([
  { prop: 'name', label: '车队名称', el: 'input' }
]);

// 获取表格列表
const getTableList = (params: DeptQuery) => {
  // 确保companyId参数被正确传递
  if (props.companyId && props.companyId > 0) {
    return getFleetListApi({ ...params, companyId: props.companyId });
  }
  // 如果没有有效的companyId，返回空数据
  return Promise.resolve({
    data: {
      current: 1,
      limit: 10,
      totalPage: 0,
      total: 0,
      rows: []
    }
  });
};

// 打开车队表单（新增/编辑）
const openFleetForm = (title: string, row: any = {}) => {
  const params = {
    title,
    row: { ...row },
    companyId: props.companyId,
    api: row.id ? updateFleetApi : createFleetApi,
    getTableList: proTableRef.value?.getTableList
  };
  fleetFormRef.value?.acceptParams(params);
};

// 删除车队
const deleteFleet = async (row: DeptRow) => {
  ElMessageBox.confirm(`确定要删除车队【${row.name}】吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await useHandleData(removeFleetApi, { ids: [row.id.toString()] }, `删除【${row.name}】车队`);
      proTableRef.value?.getTableList();
    } catch (error) {
      console.error('删除车队失败:', error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 绑定设备
const bindDevice = (row: DeptRow) => {
  // Open device binding form with fleet ID
  const params = {
    title: '绑定设备',
    fleetId: row.id,
    getTableList: proTableRef.value?.getTableList
  };
  deviceBindingFormRef.value?.acceptParams(params);
};

// 显示车辆列表
const showVehicles = (row: DeptRow) => {
  currentFleet.value = row;
  showVehicleList.value = true;
};

// 返回车队列表
const goBack = () => {
  showVehicleList.value = false;
  currentFleet.value = null;
};

// 监听公司ID变化，重新加载数据
// watch(() => props.companyId, (newVal) => {
//   if (proTableRef.value && newVal && newVal > 0) {
//     proTableRef.value.searchParam.companyId = newVal;
//     proTableRef.value.getTableList();
//   }
// });
</script>

<style scoped lang="scss">
.fleet-list {
  padding: 20px;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.font-medium {
  font-weight: 500;
}

.text-large {
  font-size: 18px;
}

.font-600 {
  font-weight: 600;
}

.mr-3 {
  margin-right: 12px;
}
</style>